package pl.edu.pw.mini.java2.Communicator.Client;

import java.io.*;

/*
 * Typy wiadomości:
 * 0 - OK, T - cokolwiek (ign.)
 * 1 - BŁĄD, T - opis.
 * 2 - Logowanie, T - dane do logowania
 * 3 - Żądanie rozmowy, T - Nazwa rozmówcy
 * 4 - Wiadomość tekstowa, T - Treść
 * 5 - Przerwanie rozmowy, T - (ign)
 * 6 - Wylogowanie
 * 7 - Zaproszenie
 * 8 - Wysylana lista kontaktów.
 * 9 - Wysylane potwierdzenie konca listy kontaktów.
 */
public class Message {
	private byte type;
	private byte[] msg;

	public final static byte OK = 0;
	public final static byte ERROR = 1;
	public final static byte LOGIN_REQUEST = 2;
	public final static byte CHAT_REQUEST = 3;
	public final static byte TEXT_MESSAGE = 4;
	public final static byte CHAT_REJECT = 5;
	public final static byte CHAT_INVITATION = 13;
	public final static byte LOGOUT_REQUEST = 6;
	public final static byte INVITE_REQUEST = 7;
	public final static byte GET_AVAILABLE_CONTACT = 9;
	public final static byte END_CONTACTS_LIST = 10;
	public final static byte GET_LEAVING_CONTACT = 11;
	public final static byte VOICE_MESSAGE = 12;

	public Message(byte type, byte[] s) {
		setType(type);
		setMessage(s);
	}

	public Message() {
		this((byte) 0, new byte[0]);
	}

	public Message(byte type) {
		this(type, new byte[0]);
	}

	public void setType(byte type) {
		this.type = type;
	}

	public byte getType() {
		return type;
	}

	public void setMessage(byte[] s) {
		msg = s;
	}

	public byte[] getMessage() {
		return msg;
	}

	public void send(DataOutputStream out) throws IOException {
		out.write(type);
		out.writeInt(msg.length);
		out.write(msg);
		out.flush();
	}

	public static Message read(DataInputStream in) throws IOException,
			EOFException {
		byte type = in.readByte();
		int len = in.readInt();
		byte[] bytes = new byte[len];
		int readed = 0;
		while (readed < len)
			readed += in.read(bytes, readed, len - readed);
		return new Message(type, bytes);
	}
}